/*
* Tencent is pleased to support the open source community by making Mars available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/

import SendMessageRequest from './proto/SendMessageRequest'
import SendMessageResponse, { Error } from './proto/SendMessageResponse'
import NanoMarsTaskWrapper from '../wrapper/remote/NanoMarsTaskWrapper'

export class TextMessageTask extends NanoMarsTaskWrapper<SendMessageRequest, SendMessageResponse> {

  private callback = null;
  private okCallback = null;
  private errorCallback = null;

  public constructor(topicName: string, from: string, text: string) {
    super(new SendMessageRequest(), new SendMessageResponse());

    // TODO: Better not holding vm

    this.request.setAccessToken("test_token");
    this.request.setFrom(from);
    this.request.setTo("all");
    this.request.setText(text);
    this.request.setTopic(topicName);
    console.info("TextMessageTask constructor" + JSON.stringify(this.request))
  }

  public onPreEncode(): void {
    // TODO: Not thread-safe here
  }

  public onPostDecode(response: SendMessageResponse): void {
    if (response.getErrCode() == Error.ERR_OK) {
      this.callback = this.okCallback;
    } else {
      this.callback = this.errorCallback;
    }
  }

  public onTaskEnd(errType: number, errCode: number): void {
    if (this.callback == null) {
      this.callback = this.onError;
    }
  }

    public onOK(onOK): TextMessageTask {
      this.okCallback = onOK;
      return this;
    }

    public onError(onError): TextMessageTask {
      this.errorCallback = onError;
      return this;
    }
}
